import modelExtend from 'dva-model-extend';
import { query, divided } from './services/contractOrders';
import { lwjPageModel } from 'utils/model';
import { routerRedux } from 'dva/router';

export default modelExtend(lwjPageModel, {
  namespace: 'profits',
  state: {
    items: [],
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    isExpand: false,
    queryParam: {},
    selectRows: [],
    selectedRowKeys: [],
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/order/profits') {
          dispatch({ type: 'query', payload: {} })
          dispatch({ type: 'clearSelectState', payload: {} })
        }
      })
    },
  },
  effects: {
    * query({ payload }, { call, put, select }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      })
      const pageOptions = yield select(({ profits }) => profits.pageOptions)
      const queryParam = yield select(({ profits }) => profits.queryParam)
      const queryPayload = {
        ...pageOptions,
        queryParam: queryParam
      }
      if (_.isEmpty(payload.profitsStatuses)) {
        queryParam.profitsStatuses = ["PENDING_PROFITS", "PROFITS", "DIVIDED_PROFITS", "DENY_PROFITS"]
      } else {
        queryParam.profitsStatuses = [payload.profitsStatuses]
      }
      queryParam.sourceSystemList = ["LWJ_SHOP","YOUZAN_SHOP"]
      const data = yield call(query, queryPayload)
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    * doDivided({ payload }, { call, put, select }) {
      yield call(divided, payload)
      yield put(routerRedux.push('/order/profits'));
    },
    * toSalesOrderDetail({ payload }, { call, put, select }) {
      yield put(routerRedux.push('/orderList/detail/' + payload.salesOrderId));
    },
  },

  reducers: {
    expandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: true
      }
    },
    unExpandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: false
      }
    },
    detailSuccess(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    onSelectChange(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    clearSelectState(state, { payload }) {
      return {
        ...state,
        ...payload,
        selectRows: [],
        selectedRowKeys: [],
      }
    },
  }
})
